<template>
  <el-container class="main-container">
    <!-- 左侧导航栏 -->
    <el-aside width="200px" class="sidebar">
      <el-menu
        :default-active="activeMenu"
        router
        class="el-menu-vertical-demo"
        @select="handleMenuSelect"
      >
        <el-menu-item index="/home">
          <el-icon><HomeFilled /></el-icon>
          <span>首页</span>
        </el-menu-item>
        <!-- <el-menu-item index="/sign-in">
          <el-icon><Calendar /></el-icon>
          <span>签到管理</span>
        </el-menu-item> -->
        <el-menu-item index="/users">
          <el-icon><User /></el-icon>
          <span>签到管理</span>
        </el-menu-item>
        <el-menu-item index="/meetings">
          <el-icon><Document /></el-icon>
          <span>会议管理</span>
        </el-menu-item>
        <el-menu-item index="/materials">
          <el-icon><Folder /></el-icon>
          <span>资料管理</span>
        </el-menu-item>
        <el-menu-item index="/guests">
          <el-icon><Star /></el-icon>
          <span>嘉宾管理</span>
        </el-menu-item>
        <el-menu-item index="/activities">
          <el-icon><Calendar /></el-icon>
          <span>活动管理</span>
        </el-menu-item>
        <el-menu-item index="/exhibitors">
          <el-icon><Shop /></el-icon>
          <span>展商管理</span>
        </el-menu-item>
        <el-menu-item index="/news">
          <el-icon><Message /></el-icon>
          <span>新闻管理</span>
        </el-menu-item>
        <el-menu-item index="/photos">
          <el-icon><Picture /></el-icon>
          <span>图片管理</span>
        </el-menu-item>
        <el-menu-item index="/meeting">
          <el-icon><VideoCamera /></el-icon>
          <span>实时会议</span>
        </el-menu-item>
      </el-menu>
    </el-aside>

    <!-- 右侧内容区域 -->
    <el-container>
      <el-header class="header">
        <div class="header-title">管理系统</div>
        <el-dropdown>
          <div class="avatar-container">
            <el-avatar :size="40" src="https://picsum.photos/40/40" />
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="showProfile">个人信息</el-dropdown-item>
              <el-dropdown-item @click="showChangePassword">修改密码</el-dropdown-item>
              <el-dropdown-item @click="handleLogout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-header>
      <el-main>
        <router-view />
      </el-main>
    </el-container>

    <!-- 个人信息对话框 -->
    <el-dialog v-model="profileDialogVisible" title="个人信息" width="30%">
      <el-form label-width="100px">
        <el-form-item label="用户ID">
          <el-input v-model="userInfo.id" disabled />
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="userInfo.username" disabled />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="userInfo.phone" disabled />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="userInfo.email" disabled />
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog v-model="changePasswordDialogVisible" title="修改密码" width="30%">
      <el-form
        ref="changePasswordFormRef"
        :model="changePasswordForm"
        :rules="changePasswordRules"
        label-width="100px"
      >
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input
            v-model="changePasswordForm.oldPassword"
            type="password"
            show-password
            placeholder="请输入旧密码"
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="changePasswordForm.newPassword"
            type="password"
            show-password
            placeholder="请输入新密码（至少6位）"
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="changePasswordForm.confirmPassword"
            type="password"
            show-password
            placeholder="请再次输入新密码"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleChangePassword">
            确认修改
          </el-button>
          <el-button @click="changePasswordDialogVisible = false">
            取消
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </el-container>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getUserInfo, changePassword } from '@/api/auth'
import type { UserInfo, ChangePasswordRequest } from '@/api/auth'
import {
  HomeFilled,
  User,
  Document,
  Folder,
  Star,
  Picture
} from '@element-plus/icons-vue'
import internal from 'stream'

const route = useRoute()
const router = useRouter()
const activeMenu = ref(route.path)

// 新增状态管理
const profileDialogVisible = ref(false)
const changePasswordDialogVisible = ref(false)
const loading = ref(false)

// 修改用户信息结构
const userInfo = ref<UserInfo>({
  id: '',
  username: '',
  phone: '',
  email: '',
})

// 修改密码表单
const changePasswordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 修改密码规则
const changePasswordRules = {
  oldPassword: [
    { required: true, message: '请输入旧密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value !== changePasswordForm.value.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// // 获取用户信息
// const fetchUserInfo = async () => {
//   try {
//     const { data } = await getUserInfo()
//     if (data) {
//       userInfo.value = data
//       console.log("userinfo",userInfo.value)
//     }
//   } catch (error: any) {
//     console.error('获取用户信息失败:', error)
//     ElMessage.error(error.response?.data?.message || '获取用户信息失败')
//     // 如果获取用户信息失败，可能是token过期，跳转到登录页
//     if (error.response?.status === 401) {
//       localStorage.removeItem('token')
//       router.push('/login')
//     }
//   }
// }

// 修改密码表单ref
const changePasswordFormRef = ref()

// 修改密码处理函数
const handleChangePassword = async () => {
  if (!changePasswordFormRef.value) return
  
  try {
    await changePasswordFormRef.value.validate()
    loading.value = true
    
    const data: ChangePasswordRequest = {
      oldPassword: changePasswordForm.value.oldPassword,
      newPassword: changePasswordForm.value.newPassword
    }
    
    await changePassword(data)
    
    ElMessage.success('密码修改成功，请重新登录')
    changePasswordDialogVisible.value = false
    // 清空表单
    changePasswordForm.value = {
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    }

    localStorage.removeItem('token')
    router.push('/login')
  } catch (error: any) {
    console.error('密码修改失败:', error)
    ElMessage.error(error.response?.data?.message || '密码修改失败')
  } finally {
    loading.value = false
  }
}

// 退出登录处理函数
const handleLogout = async () => {
  try {
    localStorage.removeItem('token')
    router.push('/login')
    ElMessage.success('退出成功')
  } catch (error: any) {
    console.error('退出失败:', error)
    ElMessage.error(error.response?.data?.message || '退出失败')
    // 即使退出失败，也清除本地token并跳转到登录页
    localStorage.removeItem('token')
    router.push('/login')
  }
}

watch(
  () => route.path,
  (newPath) => {
    activeMenu.value = newPath
  }
)

const handleMenuSelect = (index: string) => {
  activeMenu.value = index
}

const showProfile = async () => {
  try {
    const response = await getUserInfo()
    // response 现在直接就是 UserInfoResponse 类型
    userInfo.value = {
      id: response.id.toString(),
      username: response.username,
      phone: response.phone,
      email: response.email
    }
    profileDialogVisible.value = true
  } catch (error: any) {
    console.error('获取用户信息失败:', error)
    ElMessage.error(error.response?.data?.message || '获取用户信息失败')
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      router.push('/login')
    }
  }
}

const showChangePassword = () => {
  changePasswordDialogVisible.value = true
}
</script>

<style scoped>
.main-container {
  height: 100vh;
  margin-left: 200px;
}

.sidebar {
  background-color: #ffffff;
  height: 100vh;
  position: fixed;
  left: 0;
  top: 0;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
  width: 200px;
}

.header {
  background-color: #cde1f3;
  border-bottom: 2px solid #e9ecef;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  height: 60px;
  position: fixed;
  top: 0;
  left: 200px;
  right: 0;
  z-index: 1;
}

.header-title {
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
}

.avatar-container {
  cursor: pointer;
  padding: 8px;
  border-radius: 50%;
  transition: background-color 0.3s;
}

.avatar-container:hover {
  background-color: #e9ecef;
}

.el-menu {
  border-right: none;
  background-color: transparent;
  padding-left: 0;
}

.el-menu-item {
  color: #495057;
  font-weight: 500;
  transition: all 0.3s;
  padding-left: 20px !important;
  height: 48px;
  line-height: 48px;
}

.el-menu-item.is-active {
  background-color: #e3f2fd;
  color: #1976d2;
  border-left: 4px solid #1976d2;
  padding-left: 16px !important;
}

.el-menu-item:hover {
  background-color: #f8f9fa;
  color: #1976d2;
}

.el-menu-item .el-icon {
  margin-right: 8px;
  width: 20px;
  height: 20px;
  font-size: 18px;
}

.el-main {
  /* padding: 20px; */
  background-color: #ffffff;
  margin-top: 60px;
  /* margin-left: 200px; */
  min-height: calc(100vh - 60px);
}
</style> 